#! /usr/bin/python
# -*- coding: cp1250 -*-

import os
import glob
import time
import string
import checksums

# todos:
## should test on gnulinux
## should include doctests
## consider using class

def dfstats(inpfile, options=[]):

    # to speed up processing some options can be added (explicitly)
    # e.g. options=['atime', 'ctime', 'sha1', 'sha256', 'md5']
    o = options

    # 2010-10-07_2249 vp
    # []() characters sometimes used in (windows) filemes can not be used as dictionary key
    
    #for file in glob.glob(pathmask):
    #print file

    d = {}

    # retrieves the stats for the current file as a tuple
    # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
    # the tuple element mtime at index 8 is the last-modified-date
    stats = os.stat(inpfile)

    # file size
    d['size'] = stats[6]

    # file name
    #d['folder'], d['file_name'] = os.path.split(file)
    # 2010-10-07_2314 vp ... quick fix, not platform independent !!!
    d['folder'] = string.split(inpfile, '\x5C')[0]
    d['file_name'] = string.split(inpfile, '\x5C')[-1]
    if d['folder'] == d['file_name']:
       d['folder'] == '' 

    # create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),
    # weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch
    # note:  this tuple can be sorted properly by date and time
    if 'atime' in o: d['atime'] = time.localtime(stats[7])
    d['mtime'] = time.localtime(stats[8])
    if 'ctime' in o: d['ctime'] = time.localtime(stats[9])
    
    # convert date tuple to YYYY-MM-DDTHH:MM:SS format
    if 'atime' in o: s['atime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", d['atime'])
    d['mtime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", d['mtime'])
    d['mtime_plain'] = time.strftime("%Y%m%d%H%M%S", d['mtime'])
    if 'ctime' in o: d['ctime_iso'] = time.strftime("%Y-%m-%dT%H:%M:%S", d['ctime'])

    if 'md5' in o: d['md5'] = checksums.chs_md5(inpfile)
    if 'sha1' in o: d['sha1'] = checksums.chs_sha1(inpfile)
    if 'sha256' in o: d['sha256'] = checksums.chs_sha256(inpfile)

    return d

if __name__ == '__main__':
    #fs = dfstats(r'c:\*.ini', options=['sha1'])
    #fs = dfstats(r'c:\*.ini', options=['sha1'])
    #fs = dfstats(r'c:\*.ini')

    #fs = dfstats(r'c:\aft\*.*', options=['sha1'])
    #fs = dfstats(r'c:\aft\*.*', options=['sha1', 'sha256'])
    fs = dfstats(r"""C:/AFT/pepe/p_filesystem/*.*""", options=['atime'])
    
    print fs
